<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/17
 * Time: 16:08
 */

namespace app\wechat\service;

use app\common\model\User;

class LoginService {
    private static $user;

    public function __construct() {
        self::$user = new User();
    }

    public static function doLogin($code) {
        new self();
        $user_id = '';
        $data = [
            'appid' => config('wx_config')['APPID'],
            'secret' => config('wx_config')['SECRET'],
            'js_code' => $code,
            'grant_type' => 'authorization_code',
        ];
        $url = config('wx_host')['host']['wx_host'] . config('wx_host')['address']['wx_check_login'];
        $res = curlCall($url, $data);
        $result = json_decode($res, true);
        if (isset($result['openid'])) {
            $user_id = self::_saveUserInfo($result['openid']);
        }
        return $user_id;
    }

    private static function _saveUserInfo($open_id) {
        $where = [
            'open_id' => $open_id
        ];
        $userInfo = self::$user->getOneInfo($where, 'id');
        if (empty($userInfo)) {
            $data = [
                'open_id' => $open_id
            ];
            $add_res = self::$user->insertData($data);
            $user_id = $add_res;
        } else {
            $user_id = $userInfo['id'];
        }
        return $user_id;
    }


}